package com.beyond.controller;

import com.beyond.constant.ApplicationConstant;
import com.beyond.mapper.TUsersPOMapper;
import com.beyond.po.TUsersPO;
import com.beyond.po.TUsersPOExample;
import com.beyond.vo.BaseRespVO;
import com.beyond.vo.user.UserVO;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {

	private Logger logger = Logger.getLogger(LoginController.class);

	@Autowired
	private TUsersPOMapper usersPOMapper;

	@ResponseBody
	@RequestMapping(value = "v1/login")
	public BaseRespVO login(@RequestBody UserVO userVO, HttpSession session) {
		BaseRespVO respVo = new BaseRespVO();
		try {
			String username = userVO.getUsername();
			if (StringUtils.isBlank(username)) {
				throw new RuntimeException("用户名不能为空!");
			}
			String password = userVO.getPassword();
			if (StringUtils.isBlank(password)) {
				throw new RuntimeException("密码不能为空!");
			}
			TUsersPOExample example = new TUsersPOExample();
			TUsersPOExample.Criteria criteria = example.createCriteria();
			criteria.andPasswordEqualTo(password);
			criteria.andUsernameEqualTo(username);
			List<TUsersPO> usersPOS = usersPOMapper.selectByExample(example);
			if(usersPOS == null || usersPOS.size() == 0){
				respVo.setMsg("用户名或密码错误");
				respVo.setResult(ApplicationConstant.RESULT_FALTURE);
				logger.error(respVo.getMsg());
				return respVo;
			}

			session.setAttribute("userid", usersPOS.get(0).getId());
			session.setAttribute("username", usersPOS.get(0).getUsername());

			respVo.setResult(ApplicationConstant.RESULT_SUCCESS);
			respVo.setMsg("登陆成功");
		} catch (Exception e) {
			e.printStackTrace();
			respVo.setMsg(e.getMessage());
			respVo.setResult(ApplicationConstant.RESULT_FALTURE);
			logger.error(e.getMessage());
		}
		return respVo;
	}

	@ResponseBody
	@RequestMapping(value = "v1/logout")
	public BaseRespVO logout(HttpSession session) {
		BaseRespVO respVo = new BaseRespVO();
		session.removeAttribute("userid");
		session.removeAttribute("username");
		return respVo;
	}
}
